

'''

公共领取任务websocket

'''

import websocket,json,base64,sys
# 加入项目目录
sys.path.append('../')
from common.Helper import Helper
from common.config import *


try:

    import thread

except ImportError:

    import _thread as thread

import time

# 全局锁

# l = threading.Lock()

# mac地址
# 公网当前ip
# 机器码
# 线程锁


exitFlag = 0

def on_message(ws, message):

    # type 类型
    content = ( json.loads(base64.b64decode(message).decode('ascii')))

    # 订单列表任务 201 订单增量任务 200 更新授权任务 202 备注任务 203 物流任务 204 脱敏数据任务 205 评价任务 206
    # print( content )
    if int(content['type']) == 200:

        # 增量任务
        increment = base64.b64decode(content['content']).decode('ascii')

        data = {

            'type': 200,
            'content': json.loads(increment),
            'msg': '增量任务'
        }

        Helper.saveReids(data)

    elif int(content['type']) == 201:

        # 订单列表任务
        orderlist = base64.b64decode( content['content'] ).decode('ascii')

        data = {

            'type':201,
            'content':json.loads(orderlist),
            'msg':'订单列表任务'
        }

        Helper.saveReids( data )


    elif int( content['type']) == 202:

        #更新授权任务 直接返回
        from scheduler.refreshToken import authToken

        print('【API类型任务】执行拼多多refresh_token任务')

        task = base64.b64decode(content['content']).decode('ascii')

        # 转换json格式
        task = json.loads(task)

        res = authToken( task )

        data = Helper.changeBase64(json.dumps(res))

        ws.send( data )

        print('【API类型任务】access_token 已经被服务器成功接受')

    elif int(content['type'])  == 204:

        # 物流任务
        logistics = base64.b64decode( content['content'] ).decode('ascii')

        data = {

            'type': 204,
            'content': json.loads( logistics ),
            'msg': '物流任务'
        }

        Helper.saveReids(data)

    # 脱敏数据
    elif int(content['type']) == 205:

        jiemi = base64.b64decode(content['content']).decode('ascii')

        data = {

            'type': 205,
            'content': json.loads(jiemi),
            'msg': '脱敏数据任务'
        }

        Helper.saveReids(data)


    # 评价采集任务
    elif int(content['type']) == 206:

        comments = base64.b64decode(content['content']).decode('ascii')

        data = {

            'type': 206,
            'content': json.loads(comments),
            'msg': '采集评价任务'
        }

        Helper.saveReids(data)


    # 店铺评分
    elif int(content['type']) == 207:

        # 评分任务直接返回
        from crawler.score import PddScore

        s = PddScore()

        print('【爬虫类型任务】执行拼多多店铺评分采集任务')

        task = base64.b64decode(content['content']).decode('ascii')

        # 转换json格式
        task = json.loads( task )

        res = s.requestIndex( task )

        data = Helper.changeBase64(json.dumps(res))

        ws.send(data)

        print('【API类型任务】店铺评分 已经被服务器成功接受')


    else:

        print( content )

def on_error(ws, error):

    pass


def on_close(ws):

    exitFlag = False

    on_open( ws ,exitFlag)

    print("*------------------【任务接收】websocket链接断开正在尝试重新链接----------------*")

    # 如果websocket连接失败 每间隔5秒进行一次请求
    time.sleep(5)

    main()



def on_open(ws,condition=True):


    if condition:

        print('*------------------【任务接收】websocket已经建立链接---------------------*')

        # 机器码进行验证 type 类型 1
        ws.send(Helper.privateInfo( 1 ))

        def run(*args):

            while True:

                # 发送心跳包包含redis队列长度
                data = {

                    'type':9,'content':(Helper.changeBase64( json.dumps({'count':Helper.lenRedis() }) )).decode('ascii')

                }

                # 加密
                data = Helper.changeBase64( json.dumps( data ))

                ws.send( data )

                time.sleep(59)
        thread.start_new_thread( run,())


def main():

    import traceback

    try:

        websocket.enableTrace(False)

        ws = websocket.WebSocketApp( ws_connect,
                                    on_message=on_message,
                                    on_error=on_error,
                                    on_close=on_close)

        ws.on_open = on_open

        ws.run_forever(ping_interval=30, ping_timeout=5)

    except Exception :

        traceback.print_exc()

if __name__ == '__main__':

    main()